#include <stdio.h>
#include "sys/time.h"
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
//模拟长时间计算为
int calc_sqr(int num)
{
    int sqr = num * num;
    sleep(1);
    return sqr;
    
}
void *calc_thread_func(void *arg)
{
    int num = *(int *)arg;
    int *result = malloc(sizeof(int));
    *result = calc_sqr(num);
    // return result;
    //结束一个线程
    pthread_exit(result);

}
int main()
{
    int num[5] = {1,2,3,4,5};
    int sqr[5];
    struct  timeval start, end;
    gettimeofday(&start,NULL);
    pthread_t tid[5];
    //计算每个书的平方
    for(int i = 0; i < 5; i++)
    {
        // sqr[i] = calc_sqr(num[i]);
        //创建分线程进行计算
        pthread_create(&tid[i], NULL, calc_thread_func, &num[i]);
    }
    //等待分线程结束
    for(int i = 0; i < 5; i++)
    {
        void *result;
        pthread_join(tid[i], &result);
        sqr[i] = *(int *)result;
    }


    gettimeofday(&end,NULL);
    printf("消耗的时间 = %ld\n", end.tv_sec - start.tv_sec);
    //
    int total = 0;
    for(int i = 0; i < 5; i++)
    {
        total += sqr[i];
    }
    printf("total = %d\n", total);
    return 0;
}
